import os
import shutil
import time
import logging
import filecmp


log_filename = 'synchronize.log'
log_format = '%(filename)s [%(asctime)s] [%(levelname)s] %(message)s'
logging.basicConfig(format=log_format, datefmt='%Y-%m-%d %H:%M:%S %p', level=logging.DEBUG)
fileLogger = logging.getLogger('fileLogger')
fh = logging.FileHandler(log_filename)
fh.setLevel(logging.INFO)
fileLogger.addHandler(fh);
synchronPath1 = r'D:/Development/webstorm/ibmsWeb/dist'
synchronPath2 = r'D:/niagara/Daemon_User_Home4.6/stations/ibms/shared/html'

def del_file(path):
	logging.debug('remove files: ' + path)
	ls = os.listdir(path)
	for i in ls:
		c_path = os.path.join(path, i)
		if os.path.isdir(c_path):
			del_file(c_path)
		else:
			os.remove(c_path)


def synchron(synchronPath1, synchronPath2):
	try:
		leftDiffList = filecmp.dircmp(synchronPath1, synchronPath2).left_only
		rightDiffList = filecmp.dircmp(synchronPath1, synchronPath2).right_only
		commondirsList = filecmp.dircmp(synchronPath1, synchronPath2).common_dirs
		for item in leftDiffList:
			copyPath = synchronPath1 + '/' + item
			pastePath = synchronPath2 + '/' + item
			if (os.path.isdir(copyPath)):
				copyDir(copyPath, pastePath)
			else:
				shutil.copy2(copyPath, pastePath)
				fileLogger.info('copy ' + copyPath + " to " + pastePath)
		for item in rightDiffList:
			copyPath = synchronPath2 + '/' + item
			pastePath = synchronPath1 + '/' + item
			if (os.path.isdir(copyPath)):
				copyDir(copyPath, pastePath)
			else:
				shutil.copy2(copyPath, pastePath)
				fileLogger.info('copy ' + copyPath + " to " + pastePath)
		for item in commondirsList:
			copyPath = synchronPath2 + '/' + item
			pastePath = synchronPath1 + '/' + item
			syncDir(copyPath, pastePath)
	except:
		logging.debug('exception happened')
		del_file(synchronPath2)
		return


def copyDir(copyPath, pastePath):
    if (os.path.exists(pastePath)):
        synchron(copyPath, pastePath)
    else:
        # os.mkdir(pastePath)
        shutil.copytree(copyPath, pastePath)


def syncDir(copyPath, pastePath):
    copyDir(copyPath, pastePath)
    copyDir(pastePath, copyPath)


while (True):
    synchron(synchronPath1, synchronPath2)
    logging.debug('synchron run')
    time.sleep(3)
